import { appendFileSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';

// 清空 __all__.js 文件
writeFileSync('./src/device/__all__.js', '');

// 读取 JSON 文件
const inputFiles = readdirSync('./input').filter((file) => file.endsWith('.json'));

// 遍历 JSON 文件
inputFiles.forEach((file) => {
    // 读取文件内容
    const data = JSON.parse(readFileSync(`./input/${file}`).toString());

    // 获取类别信息
    const categoryAlias = data.categoryAlias;

    // 生成内容
    const content = generateContent(data);

    // 写入文件
    writeFileSync(`./src/device/${categoryAlias}.js`, content);

    // 写入 __all__.js 文件
    appendFileSync('./src/device/__all__.js', `export { default as ${categoryAlias} } from './${categoryAlias}';\n`);

    console.log(`Generated ${categoryAlias}`);
});

// 生成内容
function generateContent(data) {
    const { categoryAlias, categoryCode, categoryName, methods } = data;

    const keys = Object.keys(methods);

    // 添加类的头部
    let content = `/**
 * 自动生成！请勿修改！
 */
import { command } from '../core/command';

class ${categoryAlias} {
    static categoryCode = '${categoryCode}';

    static categoryName = '${categoryName}';

    device = {};

    opts = {};

    _to = undefined;

    constructor(opt = {}) {
        const { device, to, ...opts } = opt;

        this.device = device;
        this.opts = opts;
        this._to = to;
    }

    get categoryCode() {
        return ${categoryAlias}.categoryCode;
    }

    get categoryName() {
        return ${categoryAlias}.categoryName;
    }
`;

    // 添加类的方法
    keys.forEach((key) => {
        const { method, methodId } = methods[key];

        content += `
    ${method}(params) {
        return command({
            method: '${method}',
            methodId: '${methodId}',
            params,
            to: this.to?.[this.i] || this.to,
        });
    }
`;
    });

    // 添加类的尾部
    content += `}

export default ${categoryAlias};
`;

    return content;
}
